$(function () {
    var queryUrl = '../modulemaintainplan/list';
    var Id = getQueryString('Id');
    if(Id){
        queryUrl += '?Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        sortname: 'CREATE_DATE',
        sortorder: 'DESC',
        colModel: [
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: 'reviewStatus', name: 'reviewStatus', index: 'REVIEW_STATUS', width: 80, hidden: true},
            {label: 'moduleType', name: 'moduleType', index: 'MODULE_TYPE', width: 80, hidden: true},
            {label: '计划名称', name: 'planName', index: 'PLAN_NAME', width: 120,},
            {label: '模具号', name: 'moduleNo', index: 'MODULE_NO', width: 120},
            {label: '编制人', name: 'createUsername', index: 'CREATE_USER', width: 60},
            {
                label: '起始时间', name: 'planStartDate', index: 'PLAN_START_DATE', width: 80,
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd");
                }
            },
            {
                label: '结束时间', name: 'planEndDate', index: 'PLAN_END_DATE', width: 80,
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd");
                }
            },
            {
                label: '计划状态', index: 'PROGRESS', width: 80,
                formatter: function (value, col, row) {
                    return sysEnums.MOLD_MAINTENANCE_PLAN_PROGRESS[row.progress];
                }
            },
            {name: 'progress', hidden: true},
            {
                label: '审核详情', name: 'devCode', index: 'DEV_CODE', width: 60, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;详情</button>";
                }
            },
            {label: '详情', name: '', index: '', width: 60,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' onclick='vm.goOption(\"" + row.id + "\")'>查看</button>";
                }
            }
        ]
    });
    vm.getTypeTree();
});


var typeTree;
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "superType",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        onClick: function () {
            var node = typeTree.getSelectedNodes();
            var level = node[0].level;
            if(level>0){
                vm.q.moduleTypeName = node[0].id;
                vm.query();
            }
        }

    }
};


var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        repairUserList: [],
        moduleMaintainPlan: {
            reviewStatus: 0,
            planEndDate: '',
            planStartDate: '',
            remark: '',
            planName: '',
            moldId: '',
            id: '',
            repairUser: '',
            planEndDates:'',
            isPut:''
        },
        maintaPlanChangeRecords: {
            changeReason: '',
            remark: '',
            modelMaintaPlanId: ''
        },
        moduleError : {
            dealOpinion: '',
            isOff: 1,
            moldId: '',
            id: '',
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: '',
            progress:'',
            moduleNo:'',
            moduleTypeName:'',
        },
        remark2:"",//用于延期结束计划提交时数据
        reviewStatus:enumsToList('MOLD_MAINTENANCE_PLAN_PROGRESS'),
        // 审核参数VO
        approveParam: {
            approveIdList: [],
            status: 1,
            remark: ''
        }
    },
    methods: {
        //审核详情
        shviewOption: function (res) {
            var data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysProcess/approve',
                params: {bussinessId: data.id},
                type: 'POST',
                successCallback: function (res) {
                    var approveProcessList = res.approveProcessList;
                    if (approveProcessList.length == 0) {
                        iview.Message.error("暂无审批记录");
                        return;
                    }
                    var dom = "<div class='details'><table>";
                    for (var i = 0; i < approveProcessList.length; i++) {
                        var approveProcess = approveProcessList[i];
                        dom += '<tr><td>' + approveProcess.approveDate + '</td>';
                        dom += '<td align="left">' + approveProcess.roleName + '-' + approveProcess.name + '： ' + sysEnums.CHECK_FLAG[approveProcess.status];
                        if (approveProcess.remark) {
                            dom += '<br />备注：' + approveProcess.remark;
                        }
                        dom += '</td></tr>'
                    }
                    dom += '</table></div>'
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['500px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: dom
                    });
                }
            });
        },
        commit: function () {
            // 编制完毕后提交审核
            var planId = getSelectedRow("#jqGrid");
            if (!planId) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress !== '0' && data.progress !== '4') {
                alert('当前需求计划审核中或已通过，无需重复提交!');
                return;
            }
            Ajax.request({
                url: '../modulemaintainplan/commitApprove',
                params: {'id': data.id},
                type: 'POST',
                successCallback: function (res) {
                    alert('提交成功!');
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.moduleMaintainPlan = {
                progress: '',
                planEndDate: '',
                planStartDate: '',
                remark: '',
                planName: '',
                isPutOff:0,
                isSure:0,
                isOut:0,
                id: '',
                repairUser: '',
                moldId:'',
                moduleCode: ''
            };
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            if(vm.moduleMaintainPlan.planStartDate){
                vm.moduleMaintainPlan.planStartDate = gmt2DateStr(vm.moduleMaintainPlan.planStartDate);
            }
            if(vm.moduleMaintainPlan.planEndDate){
                vm.moduleMaintainPlan.planEndDate = gmt2DateStr(vm.moduleMaintainPlan.planEndDate);
            }
            var url = vm.moduleMaintainPlan.id == (null || '') ? "../modulemaintainplan/save" : "../modulemaintainplan/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.moduleMaintainPlan),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../modulemaintainplan/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../modulemaintainplan/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.moduleMaintainPlan = r.moduleMaintainPlan;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name,'progress':vm.q.progress,'moduleNo':vm.q.moduleNo,'moduleType':vm.q.moduleTypeName},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                progress:'',
                moduleNo:'',
                moduleTypeName:'',
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getModuleBase: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 模具清单',
                content: '../module/moduleArchiveSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getModuleArchives();
                    console.log(res);
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        var date = new Date();
                        var month = zeroFill(date.getMonth() + 1);//月
                        var day = zeroFill(date.getDate());//日
                        var days = date.getFullYear()+""+month+""+day;
                        vm.moduleMaintainPlan.moduleCode = res.moduleCode;
                        vm.moduleMaintainPlan.moldId = res.id;
                        //车间
                        //vm.moduleMaintainPlan.workshop = res.subShopName;
                        vm.moduleMaintainPlan.planName = res.moduleCode+"_"+days;
                        layer.close(index);
                    }
                }
            })
        },
        //审批
        approval: function () {
            vm.moduleMaintainPlan = {
                reviewStatus: 0
            };
            let id = getSelectedRow('#jqGrid');
            if(!id){
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress != '7') {
                alert('只有处于[部门审核]的计划才可以执行该操作！');
                return;
            }
            var _this = this;
            // 构建审批参数
            _this.approveParam = {
                approveIdList: [id],
                status: '1',
                remark: ''
            }
            openWindow({
                title: "审核",
                area: ['400px', '250px'],
                content: jQuery("#appv"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: "../modulemaintainplan/deptCheck",
                        params: JSON.stringify(_this.approveParam),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        }
                    })
                    layer.close(index);
                }
            });
        },
        getAssign: function () {
            //获取当前登录部门的维修组人员信息
            Ajax.request({
                url: '../modulemaintainplan/repairUser',
                async: false,
                successCallback: function (r) {
                    vm.repairUserList = r.list;
                    // var users = r.repairUserList;
                    // for (let user of users) {
                    //     vm.planPerson.push(user);
                    // }
                }
            })
        },
        start:function(){
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var data= getSelectedRowData("#jqGrid");
            vm.moduleMaintainPlan.id = data.id;
            vm.moduleMaintainPlan.moduleCode = data.moduleCode;
            //判断是否存在指派人
            var repUser =getAssignUser(ids[0]);
            if(repUser!= null){
                Ajax.request({
                    url:'../modulemaintainplan/start',
                    params: JSON.stringify(vm.moduleMaintainPlan),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            layer.closeAll();
                            vm.reload();
                        });
                    }
                })
            }else{
                alert("当前计划暂无领取人，无法开始流程！");
            }
        },
        //查看维护记录
        showRecord:function (id) {
            /*var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var data =getSelectedRowData("#jqGrid");
            //查询是否已经添加记录
            var i =  isHasRecord(ids[0]);
            //i=0   当前未添加记录
            if (i=="0"||i==0){
                alert("当前维护计划未有人员领用,请确认！");
            }else{*/
                openWindow({
                    type:2,
                    title: '<i class="fa fa-file-text-o"></i> 添加记录',
                    area: ['70%', '70%'],
                    content: '../module/modulePlanRecord.html?planId='+id,
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var iframeWin = window["layui-layer-iframe" + index];
                        var res = iframeWin.getFormDates();
                        /*var params ={
                            'id':ids[0],
                            'name':data.planName,
                            'file':res.file,
                            'isStop':res.isStop,
                            'isUpload':res.isUpload,
                            'reason':res.reason,
                            'remake':res.remake
                        }*/
                        // console.log(vm.regularMaintenanceRecords);
                        vm.regularMaintenanceRecords.id = i;
                        vm.regularMaintenanceRecords.file = res.file;
                        vm.regularMaintenanceRecords.isStop = res.isStop;
                        vm.regularMaintenanceRecords.isUpload = res.isUpload;
                        vm.regularMaintenanceRecords.reason = res.reason;
                        vm.regularMaintenanceRecords.remake = res.remake;

                        Ajax.request({
                            url:'../regularmaintenancerecords/addInfo',
                            params: JSON.stringify(vm.regularMaintenanceRecords),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    layer.closeAll();
                                    vm.reload();
                                });
                            }
                        })
                    }
                })
            /*}*/
        },
        isOutTime:function () {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var data =getSelectedRowData("#jqGrid");
            var isDelay=data.isDelay;
            if (isDelay=='申请中'){
                // confirm("当前任务延期申请中,确认更新延期记录?", function () {
                //     Ajax.request({
                //         url: "../modulemaintainplan/isOutTime",
                //         type: 'POST',
                //         params: {"id": data.id},
                //         async: false,
                //         successCallback: function (r) {
                //             if (r.res > 0) {//大于0时,
                //                 vm.updateOutTime();
                //             } else {
                //                 confirm("当前任务未超计划时间,确认申请延期?", function () {
                //                     layer.closeAll();
                //                     vm.updateOutTime();
                //                 })
                //             }
                //         }
                //     });
                // })
                alert("当前任务未审核!");
            } else {
                Ajax.request({
                    url: "../modulemaintainplan/isOutTime",
                    type: 'POST',
                    params: {"id": data.id},
                    async: false,
                    successCallback: function (r) {
                        if (r.res > 0) {//大于0时,
                            vm.updateOutTime();
                        } else {
                            confirm("当前任务未超计划时间,确认申请延期?", function () {
                                layer.closeAll();
                                vm.updateOutTime();
                            })
                        }
                    }
                });
            }
        },
        updateOutTime: function () {
            var id = getSelectedRow("#jqGrid");
            //获取计划结束日期
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 延期申请',
                area: ['70%', '70%'],
                content: '../module/addModuleApply.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFormDates();
                    res.ticketId = id;
                    Ajax.request({
                        url: "../maintaplanchangerecords/save",
                        params: JSON.stringify(res),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                layer.closeAll();
                                vm.reload();
                            });
                        }
                    });
                }
            });


        },
        //结束计划
        end:function(){
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var  data = getSelectedRowData("#jqGrid");
            vm.moduleMaintainPlan.id=data.id;
            vm.moduleMaintainPlan.reviewStatus=3;
            vm.moduleMaintainPlan.moduleCode=data.moduleCode;
            var resUser= getAssignUser(ids[0]);
            openWindow({
                title: "结束计划",
                area: ['300px', '200px'],
                content: jQuery("#remark_div"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    vm.moduleMaintainPlan.remark = vm.remark2;
                    Ajax.request({
                        url: '../modulemaintainplan/endProcessPlan',
                        params: JSON.stringify(vm.moduleMaintainPlan),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('当前计划已结束，所有相关执行模块已经停止！', function (index) {
                                vm.reload();
                                layer.closeAll();

                            });
                        }
                    });

                    layer.close(index);

                    // console.log(vm.remark2);
                }
            });
            if ('执行中'!=data.reviewStatus){
                alert("当前记录未执行")
            }else if(''==resUser){
                alert("当前记录未指派,请添加指派人")
            }else if('未通过'==data.reviewStatus){
                alert('当前记录审核未通过');
            }else {


            }
        },
        endPlan:function(){
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var  data = getSelectedRowData("#jqGrid");
            var resUser= getAssignUser(ids[0]);
            if('未通过'==data.reviewStatus){
                alert('当前记录审核未通过');
            } else {
                vm.moduleMaintainPlan.id=data.id;
                vm.moduleMaintainPlan.reviewStatus=6;
                vm.moduleMaintainPlan.moduleCode=data.moduleCode;

                Ajax.request({
                    url: '../modulemaintainplan/endProcessPlan',
                    params: JSON.stringify(vm.moduleMaintainPlan),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('当前计划已终止，所有相关执行模块已经停止！', function (index) {
                            vm.reload();
                            layer.closeAll();

                        });
                    }
                });
            }
        },
        //异常处理
        error:function () {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var e =hasError(ids[0]);
            if (e>0){
                alert("当前记录已经添加异常");
            } else{
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 添加异常',
                area: ['70%', '70%'],
                content: '../module/addErrorPlan.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFormDates();
                    var params = {
                        'id': ids[0], 'dealOpinion': res.dealOpinion,
                        'dealSuggest': res.dealSuggest, 'delFlag': res.delFlag,
                        'errorDisStatus': res.errorDisStatus, 'isOff': res.isOff,
                        'isReplaceSparepart': res.isReplaceSparepart
                    }
                    Ajax.request({
                        url: "../modulemaintainplan/addError",
                        params: JSON.stringify(params),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                layer.closeAll();
                                vm.reload();
                            });
                        }
                    })
                }
            });
            }
        },
        //异常处理
        dealError:function () {
            var rows = getSelectedRowDatas("#jqGrid");
            //console.log(rows)
            var ids = rows[0].id;
            console.log(ids)
           // console.log(rows[0].id)
            if (ids == null) {
                return;
            }

            var e =hasError(ids);
          //  console.log(e)
            if (e>0){
                var maintainRecord=ids
                Ajax.request({
                    url: "../moduleerror/getInfoByMaintainRecord/" + maintainRecord,
                    async: true,
                    successCallback: function (r) {
                       // console.log(r)
                        vm.moduleError = r.moduleError;
                    }
                });
                vm.moduleError.isOff=1
             //   console.log(vm.moduleError)
                openWindow({
                    title: "异常处理",
                    area: ['400px', '250px'],
                    content: jQuery("#dealError"),
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        Ajax.request({
                            url: "../moduleerror/updateOption/",
                            params: JSON.stringify(vm.moduleError),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                            }
                        })
                        layer.close(index);
                    }
                });
            } else{
                alert("当前无异常,无需处理!");
            }
        },

        goOption:function(id){
            // var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-bars"></i> 维护规程选项',//读取维护规程选项关联表数据
                content: '../module/modulemaintainrelate.html?planID=' + id
            });
        },

        //效果确认
        isSure:function(){
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            vm.moduleMaintainPlan.id = ids[0];
            vm.moduleMaintainPlan.isSure = 1;
           // console.log(data.isSure);
            if (data.reviewStatus != '结束') {
                alert("当前审核未结束");
            } else {
                if (date.isSure != '未确定') {
                    alert("当前任务已确认完成")
                } else {
                    Ajax.request({
                        url: '../modulemaintainplan/isSure',
                        params: JSON.stringify(vm.moduleMaintainPlan),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                layer.closeAll();
                                vm.reload();
                            });
                        }
                    })
                }
            }
        },
        goOptionList: function(){
            let id = getSelectedRow('#jqGrid');
            if(!id){
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            let checkStatus = data.reviewStatus;
            if(checkStatus==0||checkStatus==1){
                console.log(data.id);
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-bars"></i> 维护规程关联选项',
                    content: '../module/modulemaintainoptions_choose.html?planID='+data.id+'&moduleCode='+data.moduleCode+'&moduleType='+data.moduleType ,
                });
            }else{
                alert("此计划已经进入审核状态，禁止修改调整！");
            }
        },
        //加载模具类型树
        getTypeTree: function () {
            Ajax.request({
                url: "../moduletype/select",
                async: true,
                successCallback: function (r) {
                    var tree = r.typeList;
                    typeTree = $.fn.zTree.init($("#typeTree"), setting, tree);
                    typeTree.expandAll(true);
                }
            });
        },
    }
});
function isHasRecord(id) {
    var i;
    Ajax.request({
        url:'../regularmaintenancerecords/isHasRecord',
        type: 'POST',
        params: {"id":  id},
        async: false,
        successCallback: function (r) {
            i= r.has;
        }
   });
    return i;
}
function getAssignUser(id) {
    var  i;
    Ajax.request({
        url:'../modulemaintainplan/getAssignUser',
        type: 'POST',
        params: {"id":  id},
        async: false,
        successCallback: function (r) {
            i= r.assign;
        }
    });
    return i;
}
function hasError(id) {
    var  e;
    Ajax.request({
        url:'../modulemaintainplan/hasError',
        type: 'POST',
        params: {"id":  id},
        async: false,
        successCallback: function (r) {
            e= r.hasError;
        }
    });
    return e;
}

/**
 * 时间计算
 */
function dateCop(endDate) {
    var nowDate = new Date();
    var endDate = new Date(endDate);
    var date3 = endDate.getTime() - nowDate.getTime();
    var days=Math.floor(date3/(24*3600*1000));
    if(days<0){
        return "延期";
    }else{
        return "正常";
    }
}
